using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.API.APPLications.Commands.ImmunityInfo;
using Traceability.API.Dtos;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.APPLications.CommandHanders.ImmunityInfo
{
    /// <summary>
    /// 根据生产批次查询免疫信息查询处理器
    /// </summary>
    public class GetImmunityInfoByBatchQueryHandler : IRequestHandler<GetImmunityInfoByBatchQuery, APIResult<List<ImmunityInfoDto>>>
    {
        private readonly MyDbContext _context;

        public GetImmunityInfoByBatchQueryHandler(MyDbContext context)
        {
            _context = context;
        }

        public async Task<APIResult<List<ImmunityInfoDto>>> Handle(GetImmunityInfoByBatchQuery request, CancellationToken cancellationToken)
        {
            APIResult<List<ImmunityInfoDto>> result = new APIResult<List<ImmunityInfoDto>>();
            
            try
            {
                if (string.IsNullOrEmpty(request.ProductionBatch))
                {
                    result.Code = APIEnum.查询失败;
                    result.Message = "生产批次不能为空";
                    return result;
                }

                var items = await _context.ImmunityInfos
                    .Where(x => x.ProductionBatch.Contains(request.ProductionBatch))
                    .OrderByDescending(x => x.ID)
                    .Select(x => new ImmunityInfoDto
                    {
                        ID = x.ID,
                        RearingDays = x.RearingDays,
                        Way = x.Way,
                        Function = x.Function,
                        ProductionBatch = x.ProductionBatch
                    })
                    .ToListAsync(cancellationToken);

                result.Data = items;
                result.Code = APIEnum.查询成功;
                result.Message = $"根据生产批次 '{request.ProductionBatch}' 查询到 {items.Count} 条免疫信息";
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.查询失败;
                result.Message = $"根据生产批次查询免疫信息失败: {ex.Message}";
            }
            
            return result;
        }
    }
} 